/**
 * Project Name: renshuaipeng-auth
 * File Name: TokenInterceptor.java
 * Package Name: ren.renshuaipeng.auth.interceptor
 * Date: 2015年12月21日 上午9:52:20
 * Copyright (c) 2015, niao.shuai123@163.com All Rights Reserved.
 */
package ren.renshuaipeng.auth.web.interceptor;

import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ren.renshuaipeng.auth.common.AjaxUtil;
import ren.renshuaipeng.auth.common.JSONUtils;
import ren.renshuaipeng.util.ajax.AjaxDto;
import ren.renshuaipeng.util.anno.Token;

/**
 * ClassName: TokenInterceptor <br/>  
 * Function: 重复提交拦截器. <br/>
 * Date:     2015年12月21日 上午9:52:20 <br/>  
 * @author 任帅鹏（作者）
 * @version V1.00 （版本号）  
 * @since JDK 1.8  
 * @see
 */
public class TokenInterceptor implements HandlerInterceptor{

	private static final Logger logger=Logger.getLogger(TokenInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                boolean needSaveSession = annotation.save();
                if (needSaveSession) {
                    request.getSession().setAttribute("token", UUID.randomUUID().toString());
                }
                boolean needRemoveSession = annotation.remove();
                if (needRemoveSession) {
                    if (isRepeatSubmit(request)) {
                        logger.info("拦截到重复提交");
                        if(AjaxUtil.checkIsAjaxReq(request)){
                            AjaxUtil.ajaxJsonResponse(response, JSONUtils.obj2json(new AjaxDto(AjaxDto.TOKEN_CODE,"重复提交!")));
                        }else {
                            response.sendRedirect("/token");
                        }                        
                        return false;
                    }
                    request.getSession(false).removeAttribute("token");
                }
            }
            return true;
        } 
		
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 *
	 * @Name: isRepeatSubmit
	 * @Description: 判断是否重复提交
	 * @Author 任帅鹏（作者）
	 * @Version V1.00 （版本号）
	 * @Create Date: 2015年12月21日 上午9:57:50（创建日期）
	 * @Parameters: @param request
	 * @Parameters: @return
	 * @Return boolean
	 * @Throws
	 */
	private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession().getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }

}
